package com.dycong.common.IO.netty.AttributeMapTest;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.Attribute;

import java.util.Date;

import static com.dycong.common.IO.netty.AttributeMapTest.AttributeMapConstant.NETTY_CHANNEL_KEY;

/**
 * Created by dycong on 2017/4/17.
 * todo 得到一个整个Channel生命周期的Attribute，而ctx.attr(NETTY_CHANNEL_KEY)一个ctx对应Channel的handlers中的一个，所以在Channel生命周期不是唯一的
 */
public class HelloWorldClientHandler extends ChannelInboundHandlerAdapter{
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        // todo Attribute<NettyChannel> attr = ctx.attr(NETTY_CHANNEL_KEY); 已过时
        Attribute<NettyChannel> attr = ctx.channel().attr(NETTY_CHANNEL_KEY);
        NettyChannel nChannel = attr.get();
        if (nChannel == null) {
            NettyChannel newNChannel = new NettyChannel("HelloWorld0Client", new Date());
            nChannel = attr.setIfAbsent(newNChannel);
        } else {
            System.out.println("channelActive attributeMap 中是有值的");
            System.out.println(nChannel.getName() + "=======" + nChannel.getCreateDate());
        }
        System.out.println("HelloWorldC0ientHandler Active");
        ctx.fireChannelActive();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // todo Attribute<NettyChannel> attr = ctx.attr(NETTY_CHANNEL_KEY); 已过时
        Attribute<NettyChannel> attr = ctx.channel().attr(NETTY_CHANNEL_KEY);
        NettyChannel nChannel = attr.get();
        if (nChannel == null) {
            NettyChannel newNChannel = new NettyChannel("HelloWorld0Client", new Date());
            nChannel = attr.setIfAbsent(newNChannel);
        } else {
            System.out.println("channelRead attributeMap 中是有值的");
            System.out.println(nChannel.getName() + "=======" + nChannel.getCreateDate());
        }
        System.out.println("HelloWorldClientHandler read Message:" + msg);

        ctx.fireChannelRead(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
